﻿using Inaction.ServiceContract;
using Inaction.Rule;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Inaction.Util
{
    public class FileConfig<T> where T : FileConfig<T>, new()
    {
        static string filePath = string.Empty;
        static T instance;

        public static T Instance
        {
            get
            {
                if (instance == null)
                {
                    new T();
                    CreateInstance();
                }
                return instance;
            }
            protected set { instance = value; }
        }

        SerializeType serializeType;

        protected FileConfig(string fileName, SerializeType serializeType = SerializeType.Xml)
        {
            filePath = Inaction.Util.AppHelper.ConfigDirectory + fileName;
        }

        public virtual void Save()
        {
            var s = Inaction.ServiceContainer.GetService<ISerializerHelper>().GetSerializer(serializeType);
            s.SerializeToFile(this, filePath);
            instance = null;
        }

        protected static void CreateInstance()
        {
            if (instance != null) return;
            if (!File.Exists(filePath))
            {
                instance = new T();
                instance.Save();
            }
            using (var fs = new FileStream(filePath, FileMode.Open))
            {
                try
                {
                    var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
                    instance = (T)serializer.Deserialize(fs);

                }
                catch (Exception)
                {
                    instance = new T();
                    instance.Save();
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Close();
                        fs.Dispose();
                    }
                }
            }
        }
    }
}
